/**
 * 
 */
package fr.isima.gui;

import java.io.File;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import fr.isima.R;
import fr.isima.data.TrackProviderAdapter;
import fr.isima.model.Track;

/**
 * @author vincent
 */
public class TrackPreferences extends Activity
{
    private static final String TAG                   = "TrackPreferences";

    private EditText            textTrackName;

    private Spinner             spinMinFreqResfresh;

    private Spinner             spinMinDistResfresh;

    private CheckBox            checkBManual;

    private SharedPreferences   preferences;

    public static final String  USER_PREFERENCE       = "USER_PREFERENCE";

    private static final String EXTENSION             = ".kml";
    private static final String DIRECTORY_APP         = "/data/data/fr.isima/tracks/";
    public static final String  PREF_TRACK_NAME       = "PREF_TRACK_NAME";
    public static final String  PREF_TRACK_PATH       = "PREF_TRACK_PATH";
    public static final String  PREF_MIN_FREQ_REFRESH = "PREF_MIN_FREQ_REFRESH";
    public static final String  PREF_MIN_DIST_REFRESH = "PREF_MIN_DIST_REFRESH";
    public static final String  PREF_MANUAL_REFRESH   = "PREF_MANUAL_REFRESH";
    public static final String  PREF_TRACK_DATE       = "PREF_TRACK_DATE";

    public static final String  DEFAULT_TRACK_NAME    = "";
    public static final int     DEFAULT_FREQ_REFRESH  = 0;
    public static final int     DEFAULT_DIST_REFRESH  = 0;

    // Dialogs
    private static final int    FILE_EXITS            = 1;

    private static final int    TRACK_NAME_EMPTY      = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.track_preferences);

        textTrackName = (EditText) findViewById(R.id.text_track_name);
        spinMinFreqResfresh = (Spinner) findViewById(R.id.spinner_min_freq_refresh);
        spinMinDistResfresh = (Spinner) findViewById(R.id.spinner_min_dist_refresh);
        checkBManual = (CheckBox) findViewById(R.id.chexkbox_manual_refresh);

        populateSpinners();

        preferences = getSharedPreferences(USER_PREFERENCE, MODE_PRIVATE);

        updateUIFromPreferences();

        Button buttonOk = (Button) findViewById(R.id.buttonOk);
        buttonOk.setOnClickListener(new OnClickListener()
        {

            public void onClick(View v)
            {
                checkParameters();

            }
        });

        Button buttonCancel = (Button) findViewById(R.id.buttonCancel);
        buttonCancel.setOnClickListener(new OnClickListener()
        {

            public void onClick(View v)
            {
                Intent main = new Intent(v.getContext(), IsiHiking.class);
                startActivity(main);

            }
        });
    }

    private void startRecording()
    {
        Intent trackRecord = new Intent(this, TrackRecord.class);
        startActivity(trackRecord);
    }

    private void populateSpinners()
    {
        // Frequences
        ArrayAdapter<CharSequence> freqAdpt = ArrayAdapter.createFromResource(
                this, R.array.min_freq_options,
                android.R.layout.simple_spinner_item);
        freqAdpt
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinMinFreqResfresh.setAdapter(freqAdpt);

        // Distances
        ArrayAdapter<CharSequence> magnAdpt = ArrayAdapter.createFromResource(
                this, R.array.min_dist_options,
                android.R.layout.simple_spinner_item);
        freqAdpt
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinMinDistResfresh.setAdapter(magnAdpt);
    }

    protected void onPause()
    {
        super.onPause();

        savePreferences();
    }

    private void updateUIFromPreferences()
    {
        String trackName = preferences.getString(PREF_TRACK_NAME,
                DEFAULT_TRACK_NAME);
        int minFreqRefresh = preferences.getInt(PREF_MIN_FREQ_REFRESH,
                DEFAULT_FREQ_REFRESH);
        int minDistRefresh = preferences.getInt(PREF_MIN_DIST_REFRESH,
                DEFAULT_DIST_REFRESH);

        Log.d(TAG, "Preferences loaded (" + trackName + ", " + minFreqRefresh
                + ", " + minDistRefresh + ")");

        textTrackName.setText(trackName);

        spinMinFreqResfresh.setSelection(minFreqRefresh);

        spinMinDistResfresh.setSelection(minDistRefresh);

    }

    private void savePreferences()
    {

        Editor editor = preferences.edit();

        String trackName = textTrackName.getText().toString();
        int minFreqRefresh = spinMinFreqResfresh.getSelectedItemPosition();
        int minDistRefresh = spinMinDistResfresh.getSelectedItemPosition();

        editor
                .putString(PREF_TRACK_PATH, DIRECTORY_APP + trackName
                        + EXTENSION);
        editor.putString(PREF_TRACK_NAME, trackName);
        editor.putInt(PREF_MIN_FREQ_REFRESH, minFreqRefresh);
        editor.putInt(PREF_MIN_DIST_REFRESH, minDistRefresh);
        editor.putLong(PREF_TRACK_DATE, new Date().getTime());
        Log.d(TAG, "Preferences saved (" + trackName + ", " + minFreqRefresh
                + ", " + minDistRefresh + ")");
        editor.commit();

    }

    private void checkParameters()
    {
        String trackName = textTrackName.getText().toString();

        if (trackName.compareTo("") != 0)
        {
            File file = new File(DIRECTORY_APP + trackName + EXTENSION);

            if (file.exists())
            {
                showDialog(FILE_EXITS);
            }
            else
            {
                startRecording();
            }
        }
        else
        {
            showDialog(TRACK_NAME_EMPTY);
        }

    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        AlertDialog alert = null;

        switch (id)
        {
            case TRACK_NAME_EMPTY:
                AlertDialog.Builder emptyNameBuilder = new AlertDialog.Builder(
                        this);                
                emptyNameBuilder.setTitle(getResources().getString(
                        R.string.empty_parameter_title));
                emptyNameBuilder.setMessage("");
                String ok = getResources().getString(R.string.ok);
                emptyNameBuilder.setCancelable(false).setPositiveButton(ok,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                dialog.cancel();
                            }
                        });
                alert = emptyNameBuilder.create();
                ok = null;
                break;

            case FILE_EXITS:
                AlertDialog.Builder fileExistsBuilder = new AlertDialog.Builder(
                        this);

                String yes = getResources().getString(R.string.yes);
                String no = getResources().getString(R.string.no);
                fileExistsBuilder.setTitle(getResources().getString(
                        R.string.confirm_override_track_title));
                fileExistsBuilder.setMessage("");
                fileExistsBuilder.setCancelable(false).setPositiveButton(yes,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                deleteTrack(textTrackName.getText().toString());
                                startRecording();
                            }

                        }).setNegativeButton(no,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                dialog.cancel();
                            }
                        });
                alert = fileExistsBuilder.create();
                yes = null;
                no = null;
                break;
        }

        return alert;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog)
    {
        switch (id)
        {
            case FILE_EXITS:
                String formatExists = getResources().getString(
                        R.string.confirm_override_track);
                String messageExits = String.format(formatExists, textTrackName
                        .getText().toString());

                AlertDialog confirmDialog = (AlertDialog) dialog;
                confirmDialog.setMessage(messageExits);

                messageExits = null;
                formatExists = null;
                break;

            case TRACK_NAME_EMPTY:
                String formatExport = getResources().getString(
                        R.string.empty_parameter);
                String messageExport = String.format(formatExport,
                        getResources().getString(R.string.track_name));

                AlertDialog exportDialog = (AlertDialog) dialog;
                exportDialog.setMessage(messageExport);

                messageExport = null;
                formatExport = null;
                break;
        }
    }

    private void deleteTrack(String trackName)
    {
        TrackProviderAdapter adpt = new TrackProviderAdapter(
                getContentResolver());
        Track track = adpt.getTrackByName(trackName);

        adpt.deleteTrack(Long.parseLong(track.getId()));

        track = null;
        adpt = null;
    }
}
